package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"fmt"
	"gorm_demo/model"
	"time"
)

func main() {
	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	db.LogMode(true)
	if err != nil {
		fmt.Println(err.Error())
	}

	//updateAllFields(db)

	//updateChangedFields(db)
	updateSelectedFields(db)
}

func updateAllFields(db *gorm.DB) {
	user := model.User{}
	db.First(&user)
	fmt.Printf("select record for update %v \n", user)

	user.Name = "张三"
	user.Age = 0
	user.CreateTime = time.Now()
	user.Gender = ""
	//当save方法执行sql的时候会修改所有的字段，即使这个字段的内容没有发生改变
	db.Save(user)

}

func updateChangedFields(db *gorm.DB) {
	user := model.User{}
	db.First(&user)
	fmt.Printf("select record for update %v \n", user)
	// 更新一个属性
	db.Model(&user).Update("user_name", "张a三")
	// 根据条件更新
	db.Model(&model.User{}).Where("gender=?", "male").Update("user_name", "王五")

	user = model.User{Name: "hello", Gender: "female"}
	db.Model(&model.User{}).Updates(user)

}

func updateSelectedFields(db *gorm.DB) {
	db.Model(model.User{}).Select("user_name").Where("age=?", 13).Update(model.User{Name: "你好", Age: 18})
	db.Model(model.User{}).Omit("user_name").Where("age=?", 13).Update(model.User{Name: "你好啊", Age: 18})

}
